<?php
include_once("./_common.php");

// 년도
$this_year = date("Y");

// 년월일
$query_today = date("Y-m-d");
$query_year = substr($query_today,2,2);
$query_month = substr($query_today,5,2);
$query_date = substr($query_today,8,2);
$vi_update_date = $query_year."년 ".$query_month."월 ".$query_date."일";

// 시분초
$query_time = date("a:h:i:s");
if (substr($query_time,0,3) == "am:")
{
	$ampm = "오전 ";
}
else if (substr($query_time,0,3) == "pm:")
{
	$ampm = "오후 ";
}
$vi_update_time = $ampm.date("h : i : s");



//
$string = "mb_id = '$mb_id',
	ntc_title = '$ntc_title',
	ntc_content = '$ntc_content',
	reg_date = '$reg_date',
	regr_nm = '$regr_nm'";


if ($w == "")
{
	$sql = "INSERT
			  INTO notice_record
			   SET $string";
	$rst = sql_query($sql);
}
else if ($w == "u")
{
	$sql = "UPDATE notice_record
			   SET $string
			 WHERE id = '$id'";
	$rst = sql_query($sql);	
}
else if ($w == "d")
{
	$sql = "DELETE
			FROM	notice_record
			WHERE	id = '$id'";
	$rst = sql_query($sql);
}

echo("success");


//GCM Message Send
$apiKey = "AIzaSyA88apIf56pKLw6MrG69hNkyqhW-pmS8c8";

$messageData = "공지사항이 등록되었습니다.";

sendNotification($apiKey,$messageData);

function sendNotification($apiKey, $messageData)
{   
    // Get new notice id
    $notice_query = "SELECT id
              FROM notice_record
             order by reg_date DESC LIMIT 1";
    $rst = sql_query($notice_query);

    while($row = mysql_fetch_assoc($rst))
    {
        $list[] = $row;
    }

    $notice_id = $list[0]['id'];

    $headers = array('Content-Type:application/json ; charset=UTF-8', 'Authorization:key=AIzaSyA88apIf56pKLw6MrG69hNkyqhW-pmS8c8');

    $sql = "SELECT reg_id
              FROM gcm_table";

    $rst = sql_query($sql);

    $conidx=0;

    $arr = array();
    $arr['data'] = array();
    $arr['data']['msg'] = $messageData;
    $arr['data']['notice_id'] = $notice_id;
    $arr['registration_ids'] = array();

    while($row = mysql_fetch_array($rst))
    {
        $arr['registration_ids'][$conidx] = $row['reg_id'] ;
        $conidx++;
    }

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($arr));

    $response = curl_exec($ch);

    echo $response;
    curl_close($ch);
    //return $response;
}


?>
